package com.example.springbootdemo09.controller;

import com.example.springbootdemo09.utils.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/c")
public class CookieController {

    @GetMapping("/add")
    public R<Void> addCookie(HttpServletResponse response) {
        // 1.创建一个Cookie对象
        Cookie c1 = new Cookie("name", "Tom");
        Cookie c2 = new Cookie("age", "12");
        // 2.设置到响应对象中带给浏览器
        response.addCookie(c1);
        response.addCookie(c2);
        return R.ok("Cookie添加成功");
    }
    @GetMapping("/find")
    public R<Void> find(HttpServletRequest request) {
        // 1.从请求对象中获取到所有的cookie
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            // 2.遍历cookie数组
            for (Cookie cookie : cookies) {
                // 3.取值并打印
                System.out.println(cookie.getName() + "--" + cookie.getValue());
            }
            return R.ok("Cookie获取成功");
        }
        return R.ok("没有任何Cookie");
    }
    @GetMapping("/update")
    public R<Void> updateCookie(HttpServletResponse response) {
        // 1.创建一个Cookie对象：key值一样就会修改value值
        Cookie c1 = new Cookie("name", "Jack");
        // 2.设置到响应对象中带给浏览器
        response.addCookie(c1);
        return R.ok("Cookie修改成功");
    }
    @GetMapping("/del")
    public R<Void> del(HttpServletRequest request, HttpServletResponse response) {
        // 1.从请求对象中获取到所有的cookie
        Cookie[] cookies = request.getCookies();
        // 2.遍历cookie数组
        for (Cookie cookie : cookies) {
            // 3.判断是否是我们要操作的cookie
            if ("name".equals(cookie.getName())){
                // 4.如果是设置cookie剩余存活时间为0
                cookie.setMaxAge(0);
                // 5.必须要响应给浏览器才算设置成功
                response.addCookie(cookie);
            }
        }
        return R.ok("Cookie删除成功");
    }
}
